package com.steven.logserver.mq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 消息的生产者
 *
 * @author qinxiaohu
 *
 */
@Component
public class DirectMsgProducer implements RabbitTemplate.ConfirmCallback {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MqCommons mqCommons;

    /**
     * 由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE。非单例模式，所以不能自动注入
     */
    private RabbitTemplate rabbitTemplate;

    /**
     * 使用构造方法注入rabbitTemplate
     *
     * @param rabbitTemplate    			MQ操作模板
     */
    @Autowired
    public DirectMsgProducer(RabbitTemplate rabbitTemplate) {

        this.rabbitTemplate = rabbitTemplate;
        // 使用发布确认机制，生产者需调用setConfirmCallback(ConfirmCallback callback)
        rabbitTemplate.setConfirmCallback(this);
    }

    /**
     * 发送消息
     *
     * @param content						消息内容
     */
    public void sendMsg(Object content) {

        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(mqCommons.getExchange(), mqCommons.getRoutingKey(), content, correlationId);
    }

    /**
     * 发送消息后回调
     *
     * @param correlationData				id
     * @param ack							ack成功标识
     * @param cause							消息
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {

        logger.info(" 回调id:{}" , correlationData);
        if (ack) {
            logger.info("消息成功发送");
        }
        else {
            logger.info("消息发送失败:{}" , cause);
        }
    }
}
